package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.transaction.UserTransaction;

import com.sun.xml.rpc.processor.modeler.j2ee.xml.exceptionMappingType;

import model.Myuser;

import ejb.UserFacadeEJBRemote;

/**
 * Servlet implementation class ManageAccount
 */
@WebServlet("/ManageAccount")
public class ManageAccount extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	@EJB UserFacadeEJBRemote uf;
	@PersistenceContext EntityManager em;
	@Resource private UserTransaction utx; 
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ManageAccount() {
        super();
        // TODO Auto-generated constructor stub
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	response.sendRedirect("home.jsp");
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		String username = (String) request.getSession().getAttribute("username");
        String old_password = request.getParameter("old_password");
        String new_password = request.getParameter("new_password");
        
        
        try{
        	if(username==null){
	            out.print("Please login first! redirecting to Login...");
	            response.setHeader("Refresh","2;URL=login.jsp");
			}else if(uf.validate(username, old_password)){
				
				try{
					utx.begin();
				}
				catch(Exception ex)
				{
					ex.printStackTrace();
				}
				
            	Myuser user = uf.findUserByName(username);     
            	user.setPassword(new_password);
            	em.merge(user);
            	request.setAttribute("msg", "Password modified success");
            	
            	try{
        			utx.commit();
        		}
        		catch(Exception ex)
        		{
        			ex.printStackTrace();
        		}
            	
            	
            }else{
            	request.setAttribute("msg", "Password Incorrect");
            }        	
        	request.getRequestDispatcher("ManageAccount.jsp").forward(request, response);
        	
        }catch (Exception e){
        	e.printStackTrace();
        }
        
        
	}

}
